package com.blast.cn.ui

import android.content.Intent
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSONArray
import com.blast.cn.R
import com.blast.cn.adapter.BlastLogAdapter
import com.blast.cn.event.UploadBlastEvent
import com.blast.cn.http.MainHttps
import com.blast.cn.http.OnUploadBlastCallback
import com.blast.manager.net.ui.DetonatorListActivity
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.impl.LoadingPopupView
import com.wxl.common.AppConstant
import com.wxl.common.base.AbsActivity
import com.wxl.common.room.entity.BlastRecordEntity
import com.wxl.common.room.entity.LeiGuanBean
import com.wxl.common.room.entity.LeiGuanBlastEntity
import com.wxl.common.room.entity.LogEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.LayoutHelper
import com.wxl.common.util.NetWorkUtils
import com.wxl.common.util.ObservableUtil
import com.wxl.common.util.Toll
import kotlinx.android.synthetic.main.activity_blast_log_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class BlastLogActivity : AbsActivity() {

    var mBlastLogAdapter: BlastLogAdapter? = null
    var blastRecord = ArrayList<BlastRecordEntity>()
    var current = -1
    var loadDialog: LoadingPopupView? = null

    var page = 0
    var totalCount = 0
    var totalPage = 0


    override fun getCreateContentViewId(): Int {
        return R.layout.activity_blast_log_layout
    }

    override fun onCreateViewChanged() {

        if (loadDialog == null) {
            loadDialog = XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .asLoading("正在加载中...")
        }

        // loadDialog?.show()

        blastLogEmptyView.visibility = View.VISIBLE
        blastLogListView.visibility = View.GONE
        blastLogEmptyView.text = "正在加载数据..."

        setTopTitle("爆破日志")

        EventBus.getDefault().register(this)

        blastLogListView.layoutManager = LinearLayoutManager(this)
        // blastRecord = intent.getSerializableExtra("data") as ArrayList<BlastRecordEntity>

        DBHelper.queryBlastRecordTotalCount(object :
            ObservableUtil.Companion.OnNextCallback<Int>() {
            override fun onNext(t: Int) {
                totalCount = t
                if (totalCount > 0) {
                    val i = totalCount / AppConstant.PAGE_SIZE
                    val d = totalCount % AppConstant.PAGE_SIZE
                    if (d > 0) {
                        totalPage = i + 1
                    } else {
                        totalPage = i
                    }
                    queryBlastPage()
                }
            }
        })


        blastLogLookBtn.setOnClickListener {
            if (mBlastLogAdapter == null || mBlastLogAdapter!!.data.isEmpty()) {
                Toll.toll("没有爆破记录")
                return@setOnClickListener
            }
            current = mBlastLogAdapter!!.getSelectedPosition()
            if (blastRecord != null && current >= 0 && current < blastRecord!!.size) {
                //loadDialog?.show()
                dismissClearAllPop()
                val intent = Intent(this@BlastLogActivity, DetonatorListActivity::class.java)
                intent.putExtra("blastId", blastRecord[current].blastId)
                startActivity(intent)
            }
        }
    }


    private fun showPageCount() {
        blastLogPageText.text = "${page+1}/$totalPage"
    }


    private fun queryBlastPage() {
        if (page >= totalPage) {
            Toll.toll("已是最后一页")
            return
        }
        DBHelper.queryBlastRecordPage(page,
            object : ObservableUtil.Companion.OnNextCallback<List<BlastRecordEntity>>() {
                override fun onNext(t: List<BlastRecordEntity>) {
                    showPageCount()
                    dismissClearAllPop()
                    blastRecord.clear()
                    blastRecord.addAll(t)
                    if (blastRecord != null && blastRecord!!.isNotEmpty()) {
                        blastLogUploadBtn.setOnClickListener {
                            if (mBlastLogAdapter == null || mBlastLogAdapter!!.data.isEmpty()) {
                                Toll.toll("没有爆破记录")
                                return@setOnClickListener
                            }
                            current = mBlastLogAdapter?.getSelectedPosition()!!
                            uploadBlastRecord()
                        }
                        blastLogEmptyView.visibility = View.GONE
                        blastLogListView.visibility = View.VISIBLE
                        notifyBlastLogDataChanged()
                    } else {
                        blastLogEmptyView.text = "没有找到爆破记录"
                        blastLogEmptyView.visibility = View.VISIBLE
                        blastLogListView.visibility = View.GONE
                    }
                }
            })
    }

    private fun notifyBlastLogDataChanged() {
        if(mBlastLogAdapter == null) {
            mBlastLogAdapter = BlastLogAdapter(blastRecord)
            LayoutHelper.getDetonatorTitleViewsWidth(blastLogTitleLayout,
                object : ObservableUtil.Companion.OnNextCallback<ArrayList<Int>>() {
                    override fun onNext(t: ArrayList<Int>) {
                        mBlastLogAdapter?.setWidths(t)
                        if (mBlastLogAdapter?.getBindView() == null) {
                            mBlastLogAdapter?.bindToRecyclerView(blastLogListView)
                        }
                        mBlastLogAdapter?.setOnItemClickListener { adapter, view, position ->
                            mBlastLogAdapter?.selectItem(position)
                        }
                    }
                })
        } else {
            mBlastLogAdapter?.setNewData(blastRecord)
        }
        mBlastLogAdapter?.selectItem(0)//默认选择第一条
    }

    /**
     * 上传
     */
    private fun uploadBlastRecord() {
        if (NetWorkUtils.isNetWorkAvailable(this)) {

            if (current < 0 || current >= blastRecord!!.size) {
                loadDialog?.dismiss()
                return
            }

            if (blastRecord!![current].isUpload == 1) {
                Toll.toll("已上传")
                return
            }

            if (!loadDialog!!.isShow) {
                loadDialog?.setTitle("正在上传...")
                loadDialog?.show()
                addPop(loadDialog as BasePopupView)
            }

            blastRecord!![current].isUpload = 2
            DBHelper.updateBlastRecord(object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
                override fun onNext(t: Boolean) {
                    notifyItemDataChanged()
                    DBHelper.queryOperateLog(object :
                        ObservableUtil.Companion.OnNextCallback<List<LogEntity>>() {
                        override fun onNext(t: List<LogEntity>) {
                            blastRecord!![current].logList = ArrayList()
                            blastRecord!![current].logList.addAll(t)
                            DBHelper.queryBlastedLeiGuan(object :
                                ObservableUtil.Companion.OnNextCallback<List<LeiGuanBlastEntity>>() {
                                override fun onNext(t: List<LeiGuanBlastEntity>) {
                                    blastRecord!![current].list = JSONArray.parseArray(
                                        JSONArray.toJSONString(t),
                                        LeiGuanBean::class.java
                                    ) as ArrayList<LeiGuanBean>
                                    uploadRecord()
                                }
                            }, blastRecord!![current].blastId)
                        }
                    })
                }
            }, blastRecord!![current])
        } else {
            Toll.toll("没有网络")
            loadDialog?.dismiss()
        }
    }


    /**
     * 上传爆破记录
     */
    private fun uploadRecord() {
        MainHttps.uploadBlastRecord(
            blastRecord!![current],
            object : OnUploadBlastCallback {
                override fun onUploadBlast(isOk: Boolean) {
                    blastRecord!![current].isUpload = if (isOk) 1 else 0
                    blastRecord!![current].blastRemark = if (isOk) "有效" else ""
                    blastRecord!![current].list?.clear()
                    blastRecord!![current].logList?.clear()
                    DBHelper.updateBlastRecord(object :
                        ObservableUtil.Companion.OnNextCallback<Boolean>() {
                        override fun onNext(t: Boolean) {
                            notifyItemDataChanged()
                            if (isOk) {
                                clearLog()
                            }
                        }
                    }, blastRecord!![current])
                }
            },
            true
        )
    }

    /**
     * 来源于上传任务返回的上传结果
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun notifyUploadBlastWorkItemChanged(e: UploadBlastEvent) {
        if (blastRecord != null && blastRecord!!.isNotEmpty()) {
            var p = 0
            blastRecord?.forEach {
                if (it.blastKey == e.item.blastKey) {
                    it.isUpload = e.item.isUpload
                    mBlastLogAdapter?.notifyItemChanged(p)
                    return
                }
                p++
            }
        }
    }


    /**
     * 刷新item
     */
    private fun notifyItemDataChanged() {
        runOnUiThread(Runnable {
            loadDialog?.dismiss()
            mBlastLogAdapter?.notifyItemChanged(current)
        })
    }

    /**
     * 清除操作日志
     */
    private fun clearLog() {
        DBHelper.clearOperateLog()
    }


    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        if (mBlastLogAdapter != null) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                if (page >= 1) {
                    page--
                    queryBlastPage()
                    return true
                }
            }
            if(keyCode == KeyEvent.KEYCODE_DPAD_UP){
                if (page >= 1 && mBlastLogAdapter!!.getSelectedPosition() <= 0) {
                    page--
                    queryBlastPage()
                    return true
                }
            }
            if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                if (page >= totalPage) {
                    Toll.toll("已是最后一页")
                } else {
                    page++
                    queryBlastPage()
                    return true
                }
            }
            if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
                if(mBlastLogAdapter!!.getSelectedPosition() >= mBlastLogAdapter!!.data.size-1){
                    if (page >= totalPage) {
                        Toll.toll("已是最后一页")
                    } else {
                        page++
                        queryBlastPage()
                        return true
                    }
                }
            }
            if(mBlastLogAdapter?.getBindView() == null) {
                mBlastLogAdapter?.bindToRecyclerView(blastLogListView)
            }
            mBlastLogAdapter?.onKeyDown(keyCode, event)
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish()
        }
        if (keyCode == KeyEvent.KEYCODE_F1) {
            if (blastRecord.isNullOrEmpty()) {
                Toll.toll("没有爆破日志")
                return true
            }
            blastLogUploadBtn.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_F4) {
            if (blastRecord.isNullOrEmpty()) {
                Toll.toll("没有爆破日志")
                return true
            }
            blastLogLookBtn.performClick()
        }
        return true
    }

    override fun onDetachedFromWindow() {
        EventBus.getDefault().unregister(this)
        super.onDetachedFromWindow()
    }
}